<?php
/*
本系统由苏酷伊基于SiteHub项目二次开发
作者博客： https://www.sukuy.com/
后续更新地址： https://www.sukuy.com/navigation
作者QQ：3288637559
QQ交流群：884250547
任何第三方非官网在发布本系统时，不得删除该注释、版权信息、作者信息及官网等内容
*/
if (isset($_GET['api']) && $_GET['api'] === 'tdk') {
    header('Content-Type: application/json; charset=UTF-8');

    $rawUrl = trim($_GET['url'] ?? '');
    if (!$rawUrl) {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'Missing url']);
        exit;
    }

    if (!preg_match('~^https?://~i', $rawUrl)) {
        $rawUrl = 'http://' . $rawUrl;
    }
    $urlParts = parse_url($rawUrl);
    if (!$urlParts || empty($urlParts['host'])) {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'Invalid URL']);
        exit;
    }

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $rawUrl,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS => 3,
        CURLOPT_TIMEOUT => 7,
        CURLOPT_CONNECTTIMEOUT => 3,
        CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_HEADER => false,
        CURLOPT_ACCEPT_ENCODING => 'gzip, deflate',
    ]);
    $html = curl_exec($ch);
    $finalUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if (!$html || $httpCode >= 400) {
        http_response_code(502);
        echo json_encode(['ok' => false, 'error' => 'Fetch failed', 'code' => $httpCode]);
        exit;
    }

    libxml_use_internal_errors(true);
    $dom = new DOMDocument();
    $dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
    $xpath = new DOMXPath($dom);

    
    $title = '';
    $titleNode = $xpath->query('//title');
    if ($titleNode && $titleNode->length) {
        $title = trim($titleNode->item(0)->textContent);
    } else {
        $ogTitle = $xpath->query('//meta[@property="og:title"]');
        if ($ogTitle && $ogTitle->length) $title = trim($ogTitle->item(0)->getAttribute('content'));
    }

    
    $description = '';
    foreach (['meta[@name="description"]', 'meta[@property="og:description"]'] as $q) {
        $nodes = $xpath->query('//' . $q);
        if ($nodes && $nodes->length) {
            $description = trim($nodes->item(0)->getAttribute('content'));
            if ($description) break;
        }
    }

    
    $keywords = '';
    foreach (['meta[@name="keywords"]'] as $q) {
        $nodes = $xpath->query('//' . $q);
        if ($nodes && $nodes->length) {
            $keywords = trim($nodes->item(0)->getAttribute('content'));
            if ($keywords) break;
        }
    }

    
    $favicon = '';
    $favNodes = $xpath->query('//link[contains(translate(@rel,"ICON","icon"),"icon") and @href]');
    $base = parse_url($finalUrl ?: $rawUrl);
    $origin = ($base['scheme'] ?? 'http') . '://' . ($base['host'] ?? '');
    if ($favNodes && $favNodes->length) {
        $favicon = $favNodes->item(0)->getAttribute('href');
        if (strpos($favicon, '//') === 0) $favicon = ($base['scheme'] ?? 'http') . ':' . $favicon;
        elseif (!preg_match('~^https?://~i', $favicon)) {
            if (substr($favicon, 0, 1) !== '/') {
                $path = isset($base['path']) ? preg_replace('~/[^/]*$~', '/', $base['path']) : '/';
                $favicon = $origin . $path . $favicon;
            } else {
                $favicon = $origin . $favicon;
            }
        }
    } else {
        $favicon = $origin . '/favicon.ico';
    }

    
    $icp = '';
    if (preg_match_all('/([\x{4e00}-\x{9fa5}]?ICP备[0-9\-]+[号]?)/iu', $html, $matches)) {
        $icp = trim($matches[0][0]);
    }
    if (!$icp) {
        $nodes = $xpath->query('//footer//text() | //a[contains(@href,"beian.miit.gov.cn")]');
        foreach ($nodes as $node) {
            if (preg_match('/([\x{4e00}-\x{9fa5}]?ICP备[0-9\-]+[号]?)/iu', $node->textContent, $m)) {
                $icp = trim($m[1]);
                break;
            }
        }
    }
    if (!$icp) {
        if (preg_match('/([\x{4e00}-\x{9fa5}]?ICP备[0-9\-]+[号]?)/iu', strip_tags($html), $m)) {
            $icp = trim($m[1]);
        }
    }

    $host = $base['host'] ?? ($urlParts['host'] ?? '');
    echo json_encode([
        'ok' => true,
        'title' => $title ?: $host,
        'description' => $description,
        'keywords' => $keywords,
        'favicon' => $favicon,
        'url' => $finalUrl ?: $rawUrl,
        'host' => $host,
        'icp' => $icp,
        'code' => $httpCode,
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

if (isset($_GET['api']) && $_GET['api'] === 'categories') {
    header('Content-Type: application/json; charset=UTF-8');
    require('./includes/common.php');
    
    try {
        $categories = $DB->findAll('category', 'catename', null, 'sid asc');
        echo json_encode([
            'ok' => true,
            'categories' => $categories
        ], JSON_UNESCAPED_UNICODE);
    } catch (Exception $e) {
        echo json_encode([
            'ok' => false,
            'error' => $e->getMessage()
        ]);
    }
    exit;
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="申请收录到我爱导航网，分享优质网络资源">
<link rel="preload" href="assets/css/index-apply.css" as="style">
<link rel="preconnect" href="https://cdnjs.cloudflare.com" crossorigin>
<link rel="preconnect" href="https://cdn.jsdelivr.net" crossorigin>
<link rel="preload" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/webfonts/fa-solid-900.woff2" as="font" type="font/woff2" crossorigin>
<title>网站收录中心 - 我爱导航网</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" media="print" onload="this.media='all'">
<link rel="stylesheet" href="assets/css/index-apply.css">
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js" defer></script>
</head>
<body>
<div class="container">
    <header>
        <div class="logo"><i class="fas fa-compass"></i>收录中心</div>
        <div class="subtitle">发现优质网站，分享网络资源</div>
    </header>
    
    <div class="breadcrumb">
        <a href="index.php">首页</a> &raquo; <span>申请收录</span>
    </div>
    
    <div class="card">
        <div class="card-body">
            <div class="conditions">
                <p><strong>收录条件：</strong></p>
                <p>1、网站内容健康向上、合法合规</p>
                <p>2、网站内容、功能完善</p>
                <p>3、输入域名或完整网址获取TDK</p>
                <p>4、私自下链、位置变更、域名失效、模板相同、站点主题不符、恶意弹窗、站群的、刷量的，取消收录！</p>
                <p>5、当无法获取网站的TDK信息时请直接手工输入信息</p>
                <p>请诚信友链，不定时检查，网站打不开或位置变更的将会删除，届时只需按要求重新提交，等待审核。</p>
                <p>站长QQ：3288637559   |   QQ交流群：884250547</p>
            </div>
            <form id="apply-form" method="post">
                <div class="row">
                    <div class="col">
                        <div class="form-group">
                            <label class="form-label">网站网址<span style="color: red;">*</span></label>
                            <input type="text" class="form-input" id="url" name="url" placeholder="可输入域名，如果失败，请带上协议头">
                        </div>
                        <button type="button" class="btn btn-fetch" id="fetch-info">
                            获取TDK
                        </button>
                        <div class="loading" id="loading" style="display: none;">
                            <i class="fas fa-spinner"></i> 正在获取网站信息，请稍候...
                        </div>
                        <div class="site-info-preview" id="site-preview" style="display: none;">
                            <div class="preview-header">
                                <img src="" alt="网站图标" class="preview-favicon" id="preview-favicon" loading="lazy">
                                <div>
                                    <div class="preview-title" id="preview-title">网站标题<span style="color: red;">*</span></div>
                                    <div class="preview-url" id="preview-url">https://example.com</div>
                                </div>
                            </div>
                            <div class="preview-desc" id="preview-desc">网站描述将显示在这里...</div>
                            <div class="preview-keywords" id="preview-keywords">关键词: 示例, 测试, 网站</div>
                        </div>
                        <div class="form-group">
                            <label class="form-label">网站名称<span style="color: red;">*</span></label>
                            <input type="text" class="form-input" id="name" name="name" placeholder="请输入网站名称" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label">网站分类<span style="color: red;">*</span></label>
                            <select class="form-select" id="catename" name="catename" required>
                                <option value="">暂无分类，请联系站长新增分类</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label class="form-label">网站备案号</label>
                            <input type="text" class="form-input" id="icp" name="icp" placeholder="请输入您网站的ICP备案号(可选)">
                        </div>
                        <div class="form-group">
                            <label class="form-label">网站Favicon图标 <span style="color: red;">*</span></label>
                            <input type="text" class="form-input" id="favicon" name="favicon" placeholder="请填写你的网站favicon图标地址" required>
                        </div>
                    </div>
                    <div class="col">
                        <div class="form-group">
                            <label class="form-label">关键字词<span style="color: red;">*</span></label>
                            <input type="text" class="form-input" id="keywords" name="keywords" placeholder="请输入网站关键字，多个用逗号隔开">
                        </div>
                        <div class="form-group">
                            <label class="form-label">网站简介<span style="color: red;">*</span></label>
                            <textarea class="form-textarea" id="introduce" name="introduce" rows="6" placeholder="请输入网站简介" required></textarea>
                        </div>
                        <div class="form-group">
                            <label class="form-label">友链位置</label>
                            <input type="text" class="form-input" name="link_location" placeholder="请输入您网站上友链的位置或页面(可选)">
                        </div>
                        <div class="form-group">
                            <label class="form-label">联系方式(建议填写)</label>
                            <input type="text" class="form-input" name="contact" placeholder="请输入您的QQ或邮箱，方便审核联系">
                        </div>
                    </div>
                </div>
                <div class="form-submit">
                    <button type="submit" class="btn btn-submit">提交申请</button>
                    <button type="reset" class="btn btn-reset">重置</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    let isSubmitting = false;

    function loadCategories() {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', 'apply.php?api=categories');
        xhr.responseType = 'json';
        xhr.onload = function() {
            if (xhr.status === 200 && xhr.response.ok && xhr.response.categories.length) {
                const select = document.getElementById('catename');
                select.innerHTML = '<option value="">请选择网站分类(必选)</option>';
                xhr.response.categories.forEach(item => {
                    const option = document.createElement('option');
                    option.value = item.catename;
                    option.textContent = item.catename;
                    select.appendChild(option);
                });
            }
        };
        xhr.send();
    }
    loadCategories();
    setInterval(loadCategories, 30000);

    document.getElementById('fetch-info').addEventListener('click', function() {
        const url = document.getElementById('url').value.trim();
        if (!url) { alert('请输入网站网址'); return; }
        document.getElementById('loading').style.display = 'block';
        document.getElementById('site-preview').style.display = 'none';

        const xhr = new XMLHttpRequest();
        xhr.open('GET', 'apply.php?api=tdk&url=' + encodeURIComponent(url));
        xhr.responseType = 'json';
        xhr.onload = function() {
            document.getElementById('loading').style.display = 'none';
            if (xhr.status === 200 && xhr.response.ok) {
                const data = xhr.response;
                document.getElementById('site-preview').style.display = 'block';
                document.getElementById('preview-favicon').src = data.favicon;
                document.getElementById('preview-title').textContent = data.title;
                document.getElementById('preview-url').textContent = data.url;
                document.getElementById('preview-desc').textContent = data.description;
                document.getElementById('preview-keywords').textContent = '关键词: ' + (data.keywords || '无');

                document.getElementById('name').value = data.title;
                document.getElementById('url').value = data.url;
                document.getElementById('keywords').value = data.keywords;
                document.getElementById('favicon').value = data.favicon;
                document.getElementById('icp').value = data.icp || '';
                if (!data.icp) console.warn('未获取到备案号，请手动填写');
                if (data.description) document.getElementById('introduce').value = data.description.substring(0,200);
            } else {
                alert('获取信息失败: ' + (xhr.response?.error || '未知错误'));
            }
        };
        xhr.send();
    });

    function checkFormComplete() {
        const url = document.getElementById('url').value.trim();
        const name = document.getElementById('name').value.trim();
        const catename = document.getElementById('catename').value;
        const introduce = document.getElementById('introduce').value.trim();
        const favicon = document.getElementById('favicon').value.trim();
        if (!favicon && url) {
            let baseUrl = url.startsWith('http') ? url : 'https://' + url;
            try {
                const urlObj = new URL(baseUrl);
                document.getElementById('favicon').value = urlObj.origin + '/favicon.ico';
            } catch (e) {
                document.getElementById('favicon').value = 'https://www.example.com/favicon.ico';
            }
        }
        return url && name && catename && introduce;
    }

    document.getElementById('apply-form').addEventListener('submit', function(e) {
        e.preventDefault();
        if (isSubmitting) return;
        isSubmitting = true;

        if (!checkFormComplete()) {
            alert('请填写完整的表单信息，网站Favicon图标为必填项');
            isSubmitting = false;
            return;
        }

        const formData = new FormData(this);
        const xhr = new XMLHttpRequest();
        xhr.open('POST', 'api/apply.php?act=form');
        xhr.onload = function() {
            isSubmitting = false;
            if (xhr.status === 200) {
                try {
                    const response = JSON.parse(xhr.responseText);
                    if (response.code === 0) { alert(response.msg); window.location.reload(); }
                    else alert(response.msg || '提交失败，请重试');
                } catch(e) {
                    alert('系统提示：表单可能已成功提交，建议等待审核。');
                }
            } else {
                alert(`提交状态：服务器响应错误，状态码: ${xhr.status}\n重要提示：表单内容可能已成功提交，请等待审核。`);
            }
        };
        xhr.onerror = function() {
            isSubmitting = false;
            alert('网络连接异常，请检查网络后重试');
        };
        xhr.send(formData);
    });
});
</script>
</body>
</html>